import { Context, Next } from 'koa';
import { AppContext } from '@/types';
import { extractSubdomain } from '@/utils/helpers';
import config from '@/config';
import Tenant from '@/models/Tenant.model';
import logger from '@/utils/logger';

/**
 * 租户识别中间件
 * 从请求中识别租户并挂载到 ctx.state
 */
export default async function tenantIdentifier(ctx: Context, next: Next) {
  const appCtx = ctx as AppContext;

  // 从 Host 头中提取子域名
  const host = ctx.get('host') || '';
  const subdomain = extractSubdomain(host, config.app.domain);

  if (subdomain) {
    try {
      // 查询租户
      const tenant = await Tenant.findOne({
        where: { subdomain },
      });

      if (!tenant) {
        ctx.throw(404, '租户不存在');
      }

      // 检查租户状态
      if (!tenant.isActive()) {
        ctx.throw(403, '租户已被禁用或暂停');
      }

      // 检查试用期
      if (tenant.status === 'trial' && tenant.isTrialExpired()) {
        ctx.throw(403, '租户试用期已过期');
      }

      // 检查订阅
      if (tenant.isSubscriptionExpired()) {
        ctx.throw(403, '租户订阅已过期');
      }

      // 将租户信息挂载到 ctx.state
      appCtx.state.tenant = {
        id: tenant.id,
        name: tenant.name,
        subdomain: tenant.subdomain,
        planId: tenant.planId,
        status: tenant.status as any,
        config: tenant.config,
      };

      logger.debug(`识别到租户: ${tenant.subdomain} (${tenant.id})`);
    } catch (error) {
      if (error instanceof Error && error.message.includes('租户')) {
        throw error;
      }
      logger.error('租户识别失败:', error);
      ctx.throw(500, '租户识别失败');
    }
  }

  await next();
}


